package com.inmaytide.website.framework.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * 描述：返回的json
 */
public class JsonResult implements View {

    static Logger logger = Logger.getLogger(JsonResult.class);

    /**
     * 用于存储各属性和值
     */
    private Map<String, Object> map = new HashMap<String, Object>();
    private String testResult = "";

    /**
     * 构造方法
     */
    public JsonResult() {
    }

    public JsonResult(String msg) {
        map.put("message", StringUtils.trimToEmpty(msg));
    }

    public JsonResult(boolean success, String msg) {
        map.put("message", StringUtils.trimToEmpty(msg));
        map.put("success", success);
    }

    public String getContentType() {
        return "text/plain;charset=UTF-8";
    }

    /**
     * 设置返回到客户端的json对象的属性，success和message属性不允许设置。
     */
    public JsonResult setProperty(String key, Object value) {
        if ("success".equals(key) || "message".equals(key))
            return this;
        map.put(key, value);
        return this;
    }

    public Object getProperty(String key) {
        return map.get(key);
    }

    /**
     * 使用json返回数据供前台js进行解析.
     */
    @SuppressWarnings("unchecked")
    public void render(Map arg0, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(this.getJSONString());
        out.close();
        out = null;
    }

    /**
     * 获取json字符串，例： {"success":true,"message":"操作成功！"}
     */
    public String getJSONString() {
        if (this.map == null || this.map.size() <= 0)
            return this.testResult;
        return JSON.toJSONString(this.map);
    }

    public void setTestJSONString(String test) {
        this.testResult = test;
        logger.debug("服务端返回的数据：" + this.testResult);
    }

    public void setTestJSONString(Object data) {
        this.testResult = JSONObject.toJSONString(data);
        logger.info("服务端返回的数据：" + this.testResult);
    }

    /**
     * 是否需要不记录此信息
     *
     * @param data
     * @param isFilter
     */
    public void setTestJSONString(Object data, boolean isFilter) {
        this.testResult = JSONObject.toJSONString(data);
        if (!isFilter)
            logger.debug("服务端返回的数据：" + this.testResult);
    }


    /**
     * 设置返回的信息
     */
    public JsonResult setMsg(String msg) {
        map.put("message", StringUtils.trimToEmpty(msg));
        return this;
    }

    /**
     * 设置返回的状态
     */
    public JsonResult setSuccess(boolean success) {
        map.put("success", success);
        return this;
    }

}
